<template>
  <div class="order-success-page">
    <div class="order-success-container">
      <!-- 成功图标和提示 -->
      <div class="success-header">
        <div class="success-icon">
          <van-icon name="success" size="80" color="#67c23a" />
        </div>
        <h1>支付成功</h1>
        <p>您的订单已支付成功，可以开始打酒了</p>
      </div>
      
      <!-- 商品信息卡片 -->
      <div class="product-info-card" style="display:none">
        <div class="product-item">
          <div class="product-image">
            <img :src="productInfo.image" :alt="productInfo.name" v-if="productInfo.image" />
            <div class="no-image" v-else>暂无图片</div>
          </div>
          <div class="product-details">
            <h3 class="product-name">{{ productInfo.name || '商品名称' }}</h3>
            <p class="product-quantity">购买数量：{{ orderInfo.quantity || 100 }}ml</p>
            <p class="product-price">支付金额：¥{{ orderInfo.totalPrice || '0.00' }}</p>
          </div>
        </div>
      </div>
      
      <!-- 订单信息卡片 -->
      <div class="order-info-card">
        <div class="order-item" style="display:none">
          <span>订单编号</span>
          <span class="order-id">{{ orderId }}</span>
        </div>
        <div class="order-item">
          <span>下单时间</span>
          <span>{{ formatDateTime(orderInfo.createTime ? new Date(orderInfo.createTime) : new Date()) }}</span>
        </div>
        <div class="order-item">
          <span>有效时间</span>
          <span class="valid-time">30分钟内有效</span>
        </div>
      </div>
      
      <!-- 打酒提示 -->
      <div class="tips-card">
        <h3>打酒步骤</h3>
        <div class="tips-list">
          <div class="tip-item">
            <div class="tip-number">1</div>
            <div class="tip-content">
              <p>请在设备上按开始酒按钮</p>
            </div>
          </div>
          <div class="tip-item">
            <div class="tip-number">2</div>
            <div class="tip-content">
              <p>将酒杯放置在出酒口下方</p>
            </div>
          </div>
          <div class="tip-item highlight">
            <div class="tip-number highlight">3</div>
            <div class="tip-content">
              <p class="highlight-text">请按酒桶的开始打酒按钮</p>
              <div class="highlight-box">
                <van-icon name="warning" size="20" color="#e6a23c" />
                <span>重点提醒：请务必按下酒桶上的「开始打酒」按钮</span>
              </div>
            </div>
          </div>
          <div class="tip-item">
            <div class="tip-number">4</div>
            <div class="tip-content">
              <p>打酒完成后，请及时取走酒杯</p>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 温馨提示 -->
      <div class="reminder-card">
        <van-icon name="warning-o" class="reminder-icon" />
        <p>温馨提示：请适量饮酒，切勿酒后驾车</p>
      </div>
    </div>
    
    <!-- 底部按钮 -->
    <div class="bottom-buttons">
      <van-button 
        type="default" 
        size="large" 
        class="btn-view-order"
        @click="viewOrderDetail"
      >
        查看订单详情
      </van-button>
      <van-button 
        type="primary" 
        size="large" 
        class="btn-back-home"
        @click="backToHome"
      >
        返回首页
      </van-button>
    </div>
  </div>
</template>

<script>
console.log('OrderSuccess1')
import { api } from '../api/index.js'
export default {
  name: 'OrderSuccess',
  data() {
    console.log('OrderSuccess data initialized')
    
    // 直接在这里获取数据，不依赖生命周期钩子
    console.log('直接在data后尝试获取orderId:', this.$route.params.orderId)
    this.orderId = this.$route.params.orderId || '未知订单号'
    console.log('直接设置orderId:', this.orderId)
    
    // 尝试立即从sessionStorage获取数据
    try {
      const storedOrderInfoJson = sessionStorage.getItem('orderInfo')
      console.log('data中直接读取sessionStorage:', storedOrderInfoJson)
      if (storedOrderInfoJson) {
        const storedOrderInfo = JSON.parse(storedOrderInfoJson)
        console.log('data中解析的订单信息:', storedOrderInfo)
        // 直接返回带有初始数据的对象
        return {
          orderId: this.orderId,
          orderInfo: storedOrderInfo,
          productInfo: storedOrderInfo.productInfo || storedOrderInfo.orderDetail || {}
        }
      }
    } catch (e) {
      console.error('data中读取sessionStorage出错:', e)
    }
    
    return {
      orderId: this.orderId,
      orderInfo: {},
      productInfo: {}
    }
  },
  created() {
    console.log('OrderSuccess created hook called', 'route params:', this.$route.params)
    // 组件创建时就获取数据
    this.fetchOrderData()
  },
  mounted() {
    console.log('OrderSuccess mounted hook called', 'route params:', this.$route.params)
    console.log('Current data state:', 'has orderId:', !!this.orderId, 'has orderInfo:', !!Object.keys(this.orderInfo).length)
    // 强制调用fetchOrderData，确保一定会获取数据
    this.fetchOrderData()
    
    // 延迟清除sessionStorage中的订单信息，确保页面显示完成
    setTimeout(() => {
      console.log('延迟5秒后清除sessionStorage orderInfo')
      sessionStorage.removeItem('orderInfo')
    }, 10000) // 延长到10秒，给用户更多时间查看页面
  },
  updated() {
    console.log('updated called', 'has data:', !!(this.orderInfo.orderId || this.orderInfo.totalPrice))
    // 页面更新后再次检查数据，确保数据正确显示
    if (!this.orderInfo.orderId && !this.orderInfo.totalPrice) {
      console.log('updated: no data, calling fetchOrderData again')
      this.fetchOrderData()
    }
  },
  watch: {
    // 监听路由参数变化，确保在参数变化时重新获取数据
    '$route.params.orderId': function() {
      console.log('route params changed, calling fetchOrderData')
      this.fetchOrderData()
    }
  },
  methods: {
    // 获取订单数据 - 修复方法定义
    fetchOrderData: function() {
      console.log('\n========= fetchOrderData START =========')
      console.log('fetchOrderData called (同步方法)', 'route params:', this.$route.params)
      
      // 确保orderId正确设置
      this.orderId = this.$route.params.orderId || '未知订单号'
      console.log('Order ID set to:', this.orderId)
      
      // 重置数据
      this.orderInfo = {}
      this.productInfo = {}
      console.log('Data reset complete')
      
      // 首先从sessionStorage获取，这是从DeviceInfo跳转过来时的主要数据来源
      try {
        const storedOrderInfoJson = sessionStorage.getItem('orderInfo')
        console.log('sessionStorage orderInfo raw:', storedOrderInfoJson)
        
        if (storedOrderInfoJson) {
          try {
            const storedOrderInfo = JSON.parse(storedOrderInfoJson)
            console.log('Parsed storedOrderInfo:', storedOrderInfo)
            
            // 直接使用sessionStorage中的数据
            this.orderInfo = storedOrderInfo
            this.productInfo = storedOrderInfo.productInfo || storedOrderInfo.orderDetail || {}
            console.log('使用sessionStorage中的订单信息')
          } catch (parseError) {
            console.error('解析sessionStorage订单信息失败:', parseError)
          }
        } else {
          console.log('sessionStorage中没有订单信息')
        }
        
        // 确保订单信息至少包含必要字段
        if (!this.orderInfo.orderId && !this.orderInfo.totalPrice) {
          console.log('设置默认订单信息')
          this.orderInfo = {
            orderId: this.orderId,
            createTime: new Date().toISOString(),
            totalPrice: '0.00',
            quantity: 100,
            num: 100
          }
          this.productInfo = {
            name: '智能酒桶',
            image: '',
            description: ''
          }
        }
        
        // 确保quantity字段存在
        if (!this.orderInfo.quantity && this.orderInfo.num) {
          this.orderInfo.quantity = this.orderInfo.num
        }
        
        console.log('最终订单信息:', this.orderInfo)
        console.log('最终商品信息:', this.productInfo)
      } catch (error) {
        console.error('获取订单信息出错:', error)
        // 兜底逻辑
        this.orderInfo = {
          orderId: this.orderId,
          createTime: new Date().toISOString(),
          totalPrice: '0.00',
          quantity: 100,
          num: 100
        }
        this.productInfo = {
          name: '智能酒桶',
          image: '',
          description: ''
        }
      }
      
      console.log('========= fetchOrderData END =========\n')
    },
    
    // 格式化日期时间
    formatDateTime(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    
    // 查看订单详情
    viewOrderDetail() {
      this.$router.push(`/order-detail/${this.orderId}`)
    },
    
    // 返回首页
    backToHome() {
      this.$router.push('/')
    }
  }
}
</script>

<style scoped>
.order-success-page {
  height: 100vh;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
}

.order-success-container {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.success-header {
  text-align: center;
  margin-bottom: 30px;
}

.success-icon {
  margin-bottom: 20px;
}

.success-header h1 {
  margin: 0 0 10px 0;
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.success-header p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.product-info-card {
  width: 100%;
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.product-item {
  display: flex;
  gap: 15px;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  color: #999;
  font-size: 12px;
}

.product-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  margin: 0 0 5px 0;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.product-quantity {
  margin: 0 0 5px 0;
  font-size: 14px;
  color: #666;
}

.product-price {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.order-info-card {
  width: 100%;
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.order-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  font-size: 14px;
}

.order-item:last-child {
  margin-bottom: 0;
}

.order-id {
  font-weight: bold;
  color: #333;
}

.valid-time {
  color: #f56c6c;
  font-weight: bold;
}

.tips-card {
  width: 100%;
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.tips-card h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.tips-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.tip-item {
  display: flex;
  align-items: flex-start;
  padding: 10px 0;
}

.tip-number {
  width: 24px;
  height: 24px;
  background-color: #1989fa;
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
  margin-right: 15px;
  margin-top: 2px;
  flex-shrink: 0;
}

.tip-item.highlight {
  background-color: #fff7e6;
  border-radius: 8px;
  padding: 10px 15px;
  border-left: 4px solid #e6a23c;
}

.tip-number.highlight {
  background-color: #e6a23c;
}

.highlight-text {
  color: #e6a23c !important;
  font-weight: bold;
}

.highlight-box {
  display: flex;
  align-items: center;
  gap: 8px;
  background-color: #fff;
  padding: 10px;
  border-radius: 6px;
  margin-top: 8px;
  border: 1px solid #ffe58f;
}

.highlight-box span {
  color: #d48806;
  font-size: 13px;
  font-weight: bold;
}

.tip-content p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.reminder-card {
  width: 100%;
  background-color: #fef0f0;
  border-radius: 12px;
  padding: 15px;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.reminder-icon {
  color: #f56c6c;
  margin-right: 10px;
  font-size: 20px;
}

.reminder-card p {
  margin: 0;
  font-size: 13px;
  color: #606266;
  flex: 1;
}

.bottom-buttons {
  padding: 15px;
  background-color: #fff;
  border-top: 1px solid #eee;
  display: flex;
  gap: 15px;
}

.btn-view-order,
.btn-back-home {
  flex: 1;
  padding: 12px 0;
  border-radius: 8px;
  font-size: 16px;
}

.btn-view-order {
  border: 1px solid #1989fa;
  color: #1989fa;
  background-color: #fff;
}

.btn-back-home {
  background-color: #1989fa;
  color: #fff;
}
</style>